package com.southwind.controller;

import com.southwind.exception.ShopException;
import com.southwind.result.ResponseEnum;
import com.southwind.service.SmsService;
import com.southwind.util.RandomUtil;
import com.southwind.util.RegexValidateUtil;
import com.southwind.util.ResultVOUtil;
import com.southwind.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/send/{mobile}")
    public ResultVO send(@PathVariable("mobile") String mobile){
        if(mobile == null) throw new ShopException(ResponseEnum.SMS_MOBILE_NULL.getMsg());
        if(!RegexValidateUtil.checkMobile(mobile)) throw new ShopException(ResponseEnum.SMS_MOBILE_ERROR.getMsg());
        String code = RandomUtil.getSixBitRandom();
        boolean send = this.smsService.send(mobile, code);
        if(send) {
            this.stringRedisTemplate.opsForValue().set("uushop-sms-code-"+mobile, code);
            return ResultVOUtil.success("短信发送成功！");
        }
        return ResultVOUtil.fail(ResponseEnum.SMS_SEND_ERROR.getMsg());
    }

}
